
package test.administrator.example.com.mvptest1.demo.lce;

import android.support.annotation.NonNull;
import android.util.Log;

import java.util.List;

import test.administrator.example.com.mvptest1.framework.support.MvpQueuingBasePresenter;

public class SimpleCountriesPresenter extends MvpQueuingBasePresenter<CountriesView>
		implements CountriesPresenter {

	private static int PRESENTER_ID_FOR_LOGGING = 0;
	private final String TAG = "CountriesPresenter" + (PRESENTER_ID_FOR_LOGGING++);

	private int failingCounter = 0;
	private CountriesAsyncLoader countriesLoader;

	@Override
	public void loadCountries(final boolean pullToRefresh) {
		onceViewAttached(new ViewAction<CountriesView>() {
			@Override
			public void run(@NonNull CountriesView view) {
				view.showLoading(pullToRefresh);
			}
		});

		if (countriesLoader != null && !countriesLoader.isCancelled()) {
			countriesLoader.cancel(true);
		}

		//true代表有异常
		countriesLoader = new CountriesAsyncLoader(false,
				new CountriesAsyncLoader.CountriesLoaderListener() {

					@Override
					public void onSuccess(final List<Country> countries) {
						Log.d(TAG, "Countries callback onSuccess ");
						onceViewAttached(new ViewAction<CountriesView>() {
							@Override
							public void run(@NonNull CountriesView view) {
								Log.d(TAG, "setData()");
								view.bindData(countries);

								Log.d(TAG, "showContent()");
								view.showContent();
							}
						});
					}

					@Override
					public void onError(final Exception e) {
						Log.d(TAG, "Countries callback onError ");
						onceViewAttached(new ViewAction<CountriesView>() {
							@Override
							public void run(@NonNull CountriesView view) {
								Log.d(TAG,
										"showError(" + e.getClass().getSimpleName() + " , " + pullToRefresh + ")");
								view.showError(e, pullToRefresh);
							}
						});
					}
				});
		countriesLoader.execute();
	}

	@Override
	public void destroy() {
		super.destroy();
		if (countriesLoader != null) {
			countriesLoader.cancel(true);
		}
		Log.d(TAG, "Presenter destroyed");
	}

}
